package com.zjs.express.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期工具类
 **/
public class DateUtils {

    private static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        synchronized (sdf.get()) {
            if (date != null) {
                return sdf.get().format(date);
            } else {
                return null;
            }
        }
    }

    /**
     * 解析日期
     *
     * @param dateString
     * @return
     */
    public static Date parseDate(String dateString) {
        synchronized (sdf.get()) {
            try {
                return sdf.get().parse(dateString);
            } catch (ParseException e) {
                throw new IllegalArgumentException("Invalid date format: " + dateString, e);
            }
        }
    }

    /**
     * 格式化 LocalDate
     *
     * @param localDate
     * @return
     */
    public static String formatLocalDate(LocalDate localDate) {
        return dtf.format(localDate.atStartOfDay());
    }

    /**
     * 解析 LocalDate
     *
     * @param dateString
     * @return
     */
    public static LocalDate parseLocalDate(String dateString) {
        return LocalDateTime.parse(dateString, dtf).toLocalDate();
    }

    /**
     * 格式化 LocalDateTime
     *
     * @param localDateTime
     * @return
     */
    public static String formatLocalDateTime(LocalDateTime localDateTime) {
        return dtf.format(localDateTime);
    }

    /**
     * 解析 LocalDateTime
     *
     * @param dateString
     * @return
     */
    public static LocalDateTime parseLocalDateTime(String dateString) {
        return LocalDateTime.parse(dateString, dtf);
    }

    /**
     * 获取当前时间的 Date 对象
     *
     * @return
     */
    public static Date now() {
        return Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取当前时间的 LocalDateTime 对象
     *
     * @return
     */
    public static LocalDateTime nowLocalDateTime() {
        return LocalDateTime.now();
    }
}

